#! /usr/bin/php
<?php
/*
 * 来电弹屏守护程序
 * 适用于Asterisk 1.6+
 * @since 1.0 2014-12-16 by sutroon<14507247@qq.com>
 * @remark 启动 php -f /var/lib/asterisk/bin/amisocket.php
 * @remark memcached -d -u root -m 64 -c 1024  (/etc/rc.d/rc.local, chkconfig memcached on)
 * @remark telnet 127.0.0.1 11211, get *
 * @remark chkconfig /var/lib/asterisk/bin/amisocket.php
 */
set_time_limit(0);
// env check
if (!in_array('mysql', get_loaded_extensions())) {
    die('系统不支持mysql数据库扩展，请联系管理员开启!');
}
// 加载agi文件
include '/var/lib/asterisk/agi-bin/phpagi-asmanager.php';
// 实例化agi对象
$astman = new AGI_AsteriskManager();
$try = false;
$trycount = 0;
while ($try || $trycount < 1) {
    if (!$astman->connect("127.0.0.1:5038", 'admin', 'amp111', 'on')) {
        $try = true;
        if ($trycount > 1) {
            echo "Try Connect Asterisk $trycount" . PHP_EOL;
        }
        sleep(5);
    } else {
        $try = false;
    }
    $trycount++;
}
$trycount = 0;
echo 'Connect CTI OK!' . PHP_EOL;

// 全局配置
// 开始呼叫时间
$astman->add_event_handler('Bridge', 'Bridge_handler'); // 建立通话事件
// $astman->add_event_handler('PeerStatus', 'PeerStatus_handler'); // 当分机注册或注销时发生此事件
// $astman->add_event_handler('Newstate', 'Newstate_handler'); // 振铃事件(不用)
// $astman->add_event_handler('Unlink', 'Unlink_handler'); // 断开连接事件(不能被当成挂机事件，因为会在建立通话的时候执行到此事件)
// $astman->add_event_handler('Hangup', 'Hangup_handler'); // 挂机事件(为缓解数据库压力,暂时屏蔽 2015-1-13 by sutroon)
while (true) { //持续监听 程序相当一个守护进程持续监听 
    $astman->wait_response();
    if (date('s') < 1) {
        echo PHP_EOL . 'keeping mysql connection.';
        // mysql_query('select id from tcti_callrecord limit 1');
    }
}
$astsm->disconnect();
echo PHP_EOL . 'Disconnect OK!';

/**
 * 通话连接事件方法 for twcall
 * @param type $e
 * @param type $parameters
 * @param type $server
 * @param type $port
 * @since 2014-12-16 by sutroon
 * @remark 一次建立通话仅有一次,array ( 'Event' => 'Bridge', 'Privilege' => 'call,all', 'Bridgestate' => 'Link', 'Bridgetype' => 'core', 'Channel1' => 'Local/2000@from-internal-00000039;2', 'Channel2' => 'SIP/303-000000e1', 'Uniqueid1' => '1420081697.340', 'Uniqueid2' => '1420081697.341', 'CallerID1' => '81805', 'CallerID2' => '303', )
 */
function Bridge_handler($e, $parameters, $server, $port) {
    $filename = '/var/www/html/LSR/Conf/amisocket_conf.php';
    $ldtp_c2ie = 'Y'; // CallerID2_IS_Extension
    $ldtp_state = false;
    $ldtp_duplicate_expire = 1800;
    if (file_exists($filename)) {
        $config = include $filename;
        if (isset($config['ldtp_c2ie'])) {
            $ldtp_c2ie = $config['ldtp_c2ie'];
            $ldtp_state = $config['ldtp_state'];
        }
        if (isset($config['ldtp_duplicate_expire'])) {
            $ldtp_duplicate_expire = $config['ldtp_duplicate_expire'];
        }
    }
    // Array(    [Event] => Bridge    [Privilege] => call,all    [Bridgestate] => Link    [Bridgetype] => core    [Channel1] => SIP/ImsTest3781339-000000d3    [Channel2] => SIP/305-000000d7    [Uniqueid1] => 1457402734.235    [Uniqueid2] => 1457402743.239    [CallerID1] => 13950076987    [CallerID2] => 305)
    print_r($parameters);
    if (!$ldtp_state) {
        return;
    }
    $line = '';
    // array('CallerID2_IS_Extension'=>true);
    if ('Y' == $ldtp_c2ie) {
        $exten = $parameters['CallerID2']; // 302
        $line = $parameters['CallerID1']; // 13950076987
    } else {
        $exten = $parameters['CallerID1']; // 302
        $line = $parameters['CallerID2']; // 13950076987
    }
    if (!$line || !$exten) {
        return;
    }
    if (false) {
        db_execute("update tuser_member set conn_count=conn_count+1 where userName='$extension'");
        db_execute("insert into tcti_call_record (lineNum, extension) values ('$lineNum', '$extension')");
    }
    if (true) {
        echo 'in redis_store:::' . $exten . ', ' . $line . PHP_EOL;
        redis_store($exten, $line, $ldtp_duplicate_expire);
    }
}

// ====================== 通用函数 ======================
// 2016-3-8
function memcache_store($exten, $line, $expire) {
    $memcache = new Memcache();
    $memcache->connect('127.0.0.1', 11211);
    $duplicate = $memcache->get('temp-' . $exten); // 2015-5-13 SoChishun 判断是否重复记录
    //echo PHP_EOL,var_export('==read: $extension=' . $duplicate,true).PHP_EOL;
    echo 'dup::::' . $duplicate . ',,,' . $line;
    if (!$duplicate || $line != $duplicate) {
        echo 'in:::set(' . $exten . ',' . $line . ')';
        //echo PHP_EOL,var_export("==set: $duplicate=$lineNum=$extension");
        $memcache->set($exten, $line, MEMCACHE_COMPRESSED, 15); // 15秒没有获取则自动删除,被获取后立即删除
        $memcache->set('temp-' . $exten, $line, MEMCACHE_COMPRESSED, $expire); // 2015-5-15 SoChishun 30分钟后自动过期,30分钟内不会重复弹,解决##转分机时重复呼上一个分机的问题
    }
    $memcache->close();
}

// 2016-3-8
function redis_store($exten, $line, $expire) {
    // 实例化Redis
    $redis = new Redis();
    if (is_null($redis)) {
        exit('Redis Create Failure!');
    }
    try {
        //$redis->pconnect('127.0.0.1', 6379);
        $redis->connect('127.0.0.1', 6379);
    } catch (Exception $ex) {
        exit('Redis Connect Failure:' . $ex->getMessage());
    }
    $linex = $redis->get('LDTP_' . $exten); // 2015-5-13 SoChishun 判断是否重复记录
    //echo PHP_EOL,var_export('==read: $extension=' . $duplicate,true).PHP_EOL;
    if (!$linex || $line != $linex) {
        $redis->setex('LDTP_' . $exten, $expire, $line); // 2015-5-15 SoChishun 30分钟后自动过期,30分钟内不会重复弹,解决##转分机时重复呼上一个分机的问题(15秒没有获取则自动删除,被获取后立即删除)
    }
    $redis->close();
}

/**
 * 执行MySQL语句
 * @global array $config
 * @param string $sql
 * @since 1.0 <2015-4-8> SoChishun Added.
 */
function db_execute($sql) {
    $config = include '/var/www/html/ttf/App/Modules/XCall/Conf/config.php';
    if (!isset($config) || !$config) {
        echo '数据库配置无效' . PHP_EOL;
        exit;
    }
    $link = mysql_connect($config['DB_HOST'], $config['DB_USER'], $config['DB_PWD']);
    if (false === $link) {
        echo '数据库连接失败:' . mysql_error() . PHP_EOL;
        mysql_close($link);
        exit;
    }
    mysql_query('set names UTF8');
    mysql_select_db($config['DB_NAME']);
    $result = mysql_query($sql, $link);
    if (false === $result) {
        echo '执行失败:' . mysql_error() . PHP_EOL;
        mysql_close($link);
        exit;
    }
    mysql_close($link);
}
